#Boa:Dialog:StockExistencias

import wx
import wx.grid
import consultasBD
import utiles
import os
from decimal import Decimal

def create(parent):
    return StockExistencias(parent)

[wxID_STOCKEXISTENCIAS, wxID_STOCKEXISTENCIASBUTTON1, 
 wxID_STOCKEXISTENCIASBUTTON2, wxID_STOCKEXISTENCIASBUTTON3, 
 wxID_STOCKEXISTENCIASGRID1, wxID_STOCKEXISTENCIASRADIOBUTTON1, 
 wxID_STOCKEXISTENCIASRADIOBUTTON2, wxID_STOCKEXISTENCIASSTATICTEXT1, 
 wxID_STOCKEXISTENCIASSTATICTEXT2, wxID_STOCKEXISTENCIASSTATICTEXT3, 
 wxID_STOCKEXISTENCIASSTATICTEXT4, 
] = [wx.NewId() for _init_ctrls in range(11)]

class StockExistencias(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_STOCKEXISTENCIAS,
              name='StockExistencias', parent=prnt, pos=wx.Point(40, 135),
              size=wx.Size(598, 413), style=wx.DEFAULT_DIALOG_STYLE,
              title='Totalizador de Existencias en Stock')
        self.SetClientSize(wx.Size(590, 386))

        self.radioButton1 = wx.RadioButton(id=wxID_STOCKEXISTENCIASRADIOBUTTON1,
              label='Consulta Local (mas rapida)', name='radioButton1',
              parent=self, pos=wx.Point(8, 16), size=wx.Size(160, 13), style=0)
        self.radioButton1.SetValue(True)

        self.radioButton2 = wx.RadioButton(id=wxID_STOCKEXISTENCIASRADIOBUTTON2,
              label='Consulta directa a Sucursales', name='radioButton2',
              parent=self, pos=wx.Point(8, 32), size=wx.Size(160, 13), style=0)
        self.radioButton2.SetValue(False)

        self.button1 = wx.Button(id=wxID_STOCKEXISTENCIASBUTTON1,
              label='Procesar', name='button1', parent=self, pos=wx.Point(200,
              16), size=wx.Size(75, 23), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnProcesar,
              id=wxID_STOCKEXISTENCIASBUTTON1)

        self.button2 = wx.Button(id=wxID_STOCKEXISTENCIASBUTTON2,
              label='Limpiar', name='button2', parent=self, pos=wx.Point(288,
              16), size=wx.Size(75, 23), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnLimpiar,
              id=wxID_STOCKEXISTENCIASBUTTON2)

        self.button3 = wx.Button(id=wxID_STOCKEXISTENCIASBUTTON3, label='Salir',
              name='button3', parent=self, pos=wx.Point(504, 16),
              size=wx.Size(75, 23), style=0)
        self.button3.Bind(wx.EVT_BUTTON, self.OnSalir,
              id=wxID_STOCKEXISTENCIASBUTTON3)

        self.grid1 = wx.grid.Grid(id=wxID_STOCKEXISTENCIASGRID1, name='grid1',
              parent=self, pos=wx.Point(-72, 56), size=wx.Size(656, 272),
              style=0)

        self.staticText1 = wx.StaticText(id=wxID_STOCKEXISTENCIASSTATICTEXT1,
              label='Tipo: L (local)  D (directo)', name='staticText1',
              parent=self, pos=wx.Point(8, 336), size=wx.Size(121, 13),
              style=0)

        self.staticText2 = wx.StaticText(id=wxID_STOCKEXISTENCIASSTATICTEXT2,
              label='NOTA: -No se toma en cuenta la mercaderia que se encuentra en transferencia',
              name='staticText2', parent=self, pos=wx.Point(168, 336),
              size=wx.Size(380, 13), style=0)

        self.staticText3 = wx.StaticText(id=wxID_STOCKEXISTENCIASSTATICTEXT3,
              label='-Los valores en $ corresponden al precio de venta',
              name='staticText3', parent=self, pos=wx.Point(203, 368),
              size=wx.Size(240, 13), style=0)

        self.staticText4 = wx.StaticText(id=wxID_STOCKEXISTENCIASSTATICTEXT4,
              label='-No se toma en cuenta lo pendiente de Sincronizar',
              name='staticText4', parent=self, pos=wx.Point(203, 352),
              size=wx.Size(241, 13), style=0)

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.crearGrilla()
        self.verificarInterrupcion()

    def ajustarAnchoColumnas(self):
        for y in xrange(self.grid1.GetNumberCols()):
            self.grid1.AutoSizeColumn(y,True)

    def crearGrilla(self):
        #Fecha,Central cant,Central $,Parana cant,Parana $,Saska cant,
        #0     1            2         3           4        5
        #Saska $,Peatonal cant,Peatonal $,Tipo
        #6       7             8          9
        columnas = ['Fecha','Central\n(cant)','Central\n($)','Parana\n(cant)',\
                    'Parana\n($)','Saska\n(cant)','Saska\n($)',\
                    'Peatonal\n(cant)','Peatonal\n($)','Tipo']
        self.grid1.CreateGrid(1,len(columnas))
        for i, col in enumerate(columnas): 
            self.grid1.SetColLabelValue(i, col)

        self.grid1.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
        self.grid1.EnableEditing(False)
        self.ajustarAnchoColumnas()
        self.grid1.Refresh()

    def verificarInterrupcion(self):
        if not os.path.isfile("StockExistencias.txt"):
            f=open("StockExistencias.txt","w")
            f.close()
            print "Almacenamiento Totalizador de Existencias iniciado"
            return
        #existe archivo, por lo tanto un corte interrumpio la carga y se debe recuperar la informacion
        f=open("StockExistencias.txt","r")
        lista = f.readlines()
        f.close()
        if len(lista)==0:
            f=open("StockExistencias.txt","w")
            f.close()
            print "Almacenamiento Totalizador de Existencias iniciado"
            return
        print "Restaurando Existencias Totalizadas"
        for item in lista:
            cadena = item.split("[;]")
            if cadena[0]=="-1":
                self.grid1.DeleteRows(int(cadena[1]))
                continue
            fil = 0
            self.grid1.InsertRows(0)
            self.grid1.SetCellValue(fil,0,cadena[1]) #fecha
            self.grid1.SetCellValue(fil,1,cadena[2]) #central cant
            self.grid1.SetCellValue(fil,2,cadena[3]) #central $
            self.grid1.SetCellValue(fil,3,cadena[4]) #parana cant
            self.grid1.SetCellValue(fil,4,cadena[5]) #parana $
            self.grid1.SetCellValue(fil,5,cadena[6]) #saska cant
            self.grid1.SetCellValue(fil,6,cadena[7]) #saska $
            self.grid1.SetCellValue(fil,7,cadena[8]) #peatonal cant
            self.grid1.SetCellValue(fil,8,cadena[9]) #peatonal $
            self.grid1.SetCellValue(fil,9,cadena[10]) #local o directo

            self.grid1.SetCellAlignment(fil, 0, wx.ALIGN_CENTER, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 6, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 7, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 8, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 9, wx.ALIGN_CENTER, wx.ALIGN_CENTRE)
            if fil<(self.grid1.GetNumberRows()-1):
                continue

        self.ajustarAnchoColumnas()

    def almacenamientoTemporal(self,fila,borrar=False):
        f=open("StockExistencias.txt","a")
        encabezado = ""
        if not borrar:
            cadena = str(fila)+"[;]"+encabezado
            for item in xrange(self.grid1.GetNumberCols()):
                cadena+= str(self.grid1.GetCellValue(fila,item))+"[;]"
        else:
            cadena = "-1[;]"+str(fila)+"[;]"+encabezado
        cadena = cadena[:-3]+"\n"
        f.write(cadena)
        f.close()

    def OnSalir(self, event):
        self.Close()

    def confirmaSeguir(self):
        texto = "ATENCION:\n\n"
        texto+= "Esta por borrar los datos historicos acumulados.\n"
        texto+= "Esta operacion no puede revertirse. Perdera los\n"
        texto+= "datos acumulados si elige ACEPTAR.\n\n"
        texto+= "ACEPTAR = borra datos               CANCELAR = salir"
        import Dialog2
        confirma = Dialog2.Dialog2(self, texto)
        confirma.ShowModal()
        return confirma.getSeleccion()

    def OnLimpiar(self, event):
        if not self.confirmaSeguir():
            return
        self.grid1.ClearGrid()
        for fil in xrange(self.grid1.GetNumberRows()):
            self.grid1.DeleteRows()
        self.grid1.AppendRows()
        try:
            os.remove("StockExistencias.txt")
        except:
            print "Archivo temporal inexistente"

    def llenarGrilla(self,datos,tipo):
        fecha = utiles.obtenerFecha("d-m-Y")
        #Fecha,Central cant,Central $,Parana cant,Parana $,Saska cant,
        #0     1            2         3           4        5
        #Saska $,Peatonal cant,Peatonal $,Tipo
        #6       7             8          9
        self.grid1.InsertRows(0)
        self.grid1.SetCellValue(0,0,fecha)
        for item in datos:
            cantidad = str(Decimal(str(item["cant"])))
            precio = str(Decimal(str(item["pventa"])).quantize(Decimal("0.10")))
            if item["sucursal"]=="1":
                self.grid1.SetCellValue(0,1,cantidad)
                self.grid1.SetCellValue(0,2,precio)
            elif item["sucursal"]=="2":
                self.grid1.SetCellValue(0,3,cantidad)
                self.grid1.SetCellValue(0,4,precio)
            elif item["sucursal"]=="3":
                self.grid1.SetCellValue(0,5,cantidad)
                self.grid1.SetCellValue(0,6,precio)
            elif item["sucursal"]=="4":
                self.grid1.SetCellValue(0,7,cantidad)
                self.grid1.SetCellValue(0,8,precio)
        self.grid1.SetCellValue(0,9,tipo)

        self.grid1.SetCellAlignment(0, 0, wx.ALIGN_CENTER, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(0, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(0, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(0, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(0, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(0, 5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(0, 6, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(0, 7, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(0, 8, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(0, 9, wx.ALIGN_CENTER, wx.ALIGN_CENTRE)

        self.ajustarAnchoColumnas()
        
        self.almacenamientoTemporal(0)

    def procesaLocal(self,sucursal=1):
        print "suc:",sucursal,
        suc = str(sucursal)
        r1 = "SELECT SUM(p5.stock) AS cant,SUM(total) AS pventa "
        r2 = "FROM "
        r3 = "  (SELECT p3.stock,p4.preciolt1,p4.preciolt1*p3.stock as total "
        r4 = "   FROM "
        r5 = "     (SELECT p1.ptc,p2.codsussan,p1.stock "
        r6 = "      FROM "
        r7 = "        (SELECT ptc,stock FROM stock WHERE stock<>0 AND sucursal="+suc+") AS p1, "
        r8 = "        producto_talle_color AS p2 "
        r9 = "      WHERE p1.ptc=p2.id) AS p3, "
        r0 = "     productos AS p4 "
        rA = "   WHERE p4.codsussan=p3.codsussan) AS p5 "
        rB = "WHERE 1 "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA+rB
        resultados = consultasBD.ordenCrudaDict(sql)
        return resultados
    
    def procesaRemoto(self,sucursal):
        print "suc:",sucursal,
        suc = str(sucursal)
        r1 = "SELECT SUM(p5.stock) AS cant,SUM(total) AS pventa "
        r2 = "FROM "
        r3 = "  (SELECT p3.stock,p4.preciolt1,p4.preciolt1*p3.stock as total "
        r4 = "   FROM "
        r5 = "     (SELECT p1.ptc,p2.codsussan,p1.stock "
        r6 = "      FROM "
        r7 = "        (SELECT ptc,stock FROM stock WHERE stock<>0 AND sucursal="+suc+") AS p1, "
        r8 = "        producto_talle_color AS p2 "
        r9 = "      WHERE p1.ptc=p2.id) AS p3, "
        r0 = "     productos AS p4 "
        rA = "   WHERE p4.codsussan=p3.codsussan) AS p5 "
        rB = "WHERE 1 "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA+rB
        resultados = consultasBD.ordenCrudaDictRemota(sql,int(suc)-1)
        return resultados

    def OnProcesar(self, event):
        print "Procesando",
        sql = "SELECT codsucursal FROM sucursales WHERE 1"
        resultados = consultasBD.ordenCruda(sql)
        if self.radioButton1.GetValue():
            print "-> local",
            datos = []
            for item in resultados:
                sucursal = item[0]
                aux = self.procesaLocal(sucursal)
                aux = aux[0]
                aux["sucursal"]=sucursal
                datos.append(aux)
            print
            self.llenarGrilla(datos,"L")
        else:
            print "-> remoto",
            datos = []
            marca = False
            for item in resultados:
                sucursal = item[0]
                aux,conectado = self.procesaRemoto(sucursal)
                if not conectado:
                    marca = True
                aux = aux[0]
                aux["sucursal"]=sucursal
                datos.append(aux)
            print
            if marca:
                texto = "Atencion: se perdio la\n"
                texto+= "comunicacion con alguna sucursal"
                utiles.mensaje(None,texto)
            self.llenarGrilla(datos,"D")
